package com.sky.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class QiniuUpload {
    private String accessKey;

    private String secretKey;

    private String bucket;

    private String domain;

    private String directory;

    /**
     * @return
     * @method getUploadToken
     * @description 获取上传凭证 (用于客户端直传)
     */
    public String getUploadToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    /**
     * @return
     * @method getOverrideUploadToken
     * @description 获取上传覆盖凭证 (用于客户端直传)
     */
    public String getOverrideUploadToken(String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, key);
        return upToken;
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 创建上传token
        String upToken = getUploadToken();
        // TODO 设置上传配置，Region要与存储空间所属的存储区域保持一致
        Configuration cfg = new Configuration(Region.huadongZheJiang2());
        // 创建上传管理器
        UploadManager uploadManager = new UploadManager(cfg);
        String originalFilename = file.getOriginalFilename();
        // 构造文件目录和文件名
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //指定上传的目录 会自动识别
        String fileKey = directory + UUID.randomUUID().toString() + suffix;
        Response response = uploadManager.put(file.getInputStream(), fileKey, upToken, null, null);

        if (response.statusCode == 200) {
            return getDomain() + "/" + fileKey;
        } else {
            return null;
        }

    }

    /**
     * 文件删除
     */
    public void deleteFile(String imageName) {
        log.info("删除文件：" + imageName);
        //去掉域名部分就是需要的key
        String key = imageName.substring(imageName.indexOf(domain) + domain.length() +1);
        log.info("key" + key);
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response delete = bucketManager.delete(bucket, key);
            log.info("图片删除结果：" + delete.toString());
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            //TODO 应该将删除失败的图片信息保存到数据库，定时任务删除
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
